package com.atuguigu.flink.Day03;

import com.atuguigu.flink.Day01.Singlesensor.SensorSource;
import com.atuguigu.flink.sensor.SendsorReading;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;

public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //第一条流
        DataStreamSource<SendsorReading> sensorStream = env.addSource(new SensorSource());
        //第二条流
        DataStreamSource<Tuple2<String, Long>> switchStream = env.fromElements(Tuple2.of("sensor_2", 10 * 1000L));

        sensorStream
                .keyBy(r->r.id)
                .connect(switchStream.keyBy(r->r.f0))
                .process(new SwitchFileter())
                .print();



        env.execute();
    }

    public static class SwitchFileter extends CoProcessFunction<SendsorReading,Tuple2<String,Long>,SendsorReading> {
        private ValueState<Boolean> forwarding;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            forwarding = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("switch", Types.BOOLEAN));
        }

        @Override
        public void processElement1(SendsorReading sendsorReading, Context context, Collector<SendsorReading> collector) throws Exception {
            //如果进来第一条流，开关未打开，不会向下游发送数据
            if(forwarding.value()!=null && forwarding.value()){
                collector.collect(sendsorReading);//满足条件，开始发送
            }

        }

        @Override
        public void processElement2(Tuple2<String, Long> stringLongTuple2, Context context, Collector<SendsorReading> collector) throws Exception {
            //第二条流，进来后，打开开关，
            forwarding.update(true);
            //设置10s后，打开定时器开关
            context.timerService().registerProcessingTimeTimer(context.timerService().currentProcessingTime() + stringLongTuple2.f1);

        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<SendsorReading> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            forwarding.clear();//关闭开关.
        }
    }
}
